<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\user_center\home;
use app\common\controller\AuthCheck;
use think\facade\Cache;
/**
 * 用户公开控制器，不经过权限认证
 * @package app\user\admin
 */
class Publics extends AuthCheck
{
    /**
     * 用户登录
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function login_mobile(){
        //参数接收
        $params = $this->getParams(1);//0 get 1 post 
        $mobile    		= intval(isset($params["mobile"]) ? $params["mobile"] : 0);
        $code      		= intval(isset($params["code"]) ? $params["code"] : 0);
        $login_type     = intval(isset($params["login_type"]) ? $params["login_type"] : 0);
        $f_uid   		= intval(isset($params["f_uid"]) ? $params["f_uid"] : 0);
        //数据验证
        $Validate = validate('Publics', 'validate\publics');
        if( !$Validate -> scene('login_mobile') -> check($params) ){
            json_out(-1001, $Validate -> getError(), (object)[]);//验证失败
        }
        //逻辑处理
        $list = controller('Userlogic', 'logic\user') -> login_mobile($mobile, $code, $f_uid);

        //数据返回
        if($list['code'] == 200){
            json_out(200, '登录成功', (object)$list['data']);      
        }else{
            json_out($list['code'], $list['message'], (object)[]);      
        }
    }

    /**
     * 一键登录
     * @author shiqiang
     * @return mixed
     */
    public function login_mobile_oneclick(){
        //参数接收
        $params = $this->getParams(1);//0 get 1 post
        $access_code    = isset($params["access_code"]) ? $params["access_code"] : 0;
        //数据验证
        $Validate = validate('Publics', 'validate\publics');
        if( !$Validate -> scene('login_mobile_oneclick') -> check($params) ){
            json_out(-1001, $Validate -> getError(), (object)[]);//验证失败
        }
        //逻辑处理
//        $list = controller('Userlogic', 'logic\user') -> login_mobile_oneclick($access_code);
        $list = controller('Userlogic', 'logic\user') -> login_mobile_obtain($access_code);

        //数据返回
        if($list['code'] == 200){
            json_out(200, '登录成功', (object)$list['data']);
        }else{
            json_out($list['code'], $list['message'], (object)[]);
        }
    }
	
	/**
	 * 微信注册/登录
	 * @author shiqiang <9761622041@qq.com>
	 * @return mixed
	 */
	public function register_wechat(){
		//参数接收
        $params = $this->getParams(1);//0 get 1 post 
		
		$openid    		= isset($params["openid"]) ? $params["openid"] : '';
		$nick_name 		= isset($params["nick_name"]) ? $params["nick_name"] : '';
		$avatar_url    	= isset($params["avatar_url"]) ? $params["avatar_url"] : '';
		$unionid  		= isset($params["unionid"]) ? $params["unionid"] : '';
		
		//数据验证
        $Validate = validate('Publics', 'validate\publics');
        if( !$Validate -> scene('register_wechat') -> check($params) ){
            json_out(-1001, $Validate -> getError(), (object)[]);//验证失败
        }
		
		//逻辑处理
        $list = controller('Userlogic', 'logic\user') -> register_wechat($openid, $nick_name, $avatar_url, $unionid);
		
		//数据返回
        if($list['code'] == 200){
            json_out(200, '登录成功', (object)$list['data']);      
        }else{
            json_out($list['code'], $list['message'], (object)[]);      
        }
	}
	
	/**
	 * 苹果用户注册/登录
	 * @author shiqiang <9761622041@qq.com>
	 * @return mixed
	 */
	public function register_apple(){
		//参数接收
        $params = $this->getParams(1);//0 get 1 post 
		
		$apple_id    	= isset($params["apple_id"]) ? $params["apple_id"] : '';
		$nick_name 		= isset($params["nick_name"]) ? $params["nick_name"] : '';
		$avatar_url    	= isset($params["avatar_url"]) ? $params["avatar_url"] : '';
		
		//数据验证
        $Validate = validate('Publics', 'validate\publics');
        if( !$Validate -> scene('register_apple') -> check($params) ){
            json_out(-1001, $Validate -> getError(), (object)[]);//验证失败
        }
		
		//逻辑处理
        $list = controller('Userlogic', 'logic\user') -> register_apple($apple_id, $nick_name, $avatar_url);
		
		//数据返回
        if($list['code'] == 200){
            json_out(200, '登录成功', (object)$list['data']);      
        }else{
            json_out($list['code'], $list['message'], (object)[]);      
        }
	}

	/**
	 * 短信发送
	 * @author shiqiang <9761622041@qq.com>
	 * @return mixed
	 */
	public function sms_sending(){
		//参数接收
        $params 		= $this->getParams(1);//0 get 1 post 
		$uid 			= intval(isset($params["user_id"]) ? $params["user_id"] : 0);//非必传
		$mobile 		= intval(isset($params["mobile"]) ? $params["mobile"] : 0);
		$mobile_type 	= intval(isset($params["mobile_type"]) ? $params["mobile_type"] : '');
		
		//数据验证
        $Validate = validate('Publics', 'validate\publics');
        if( !$Validate -> scene('sms_sending') -> check($params) ){
            json_out(-1001, $Validate -> getError());//验证失败
        }
		
		//逻辑处理
        $list = controller('Userlogic', 'logic\user') -> sms_sending($uid, $mobile, $mobile_type);
		
		
		//数据返回
		if($list['code'] == 200){
			json_out(200, '发送成功');
		}else{
			json_out($list['code'], $list['message']);
		}
	}
	
	
	/**
	 * 用户详情信息
	 * @author shiqiang <9761622041@qq.com>
	 * @return mixed
	 */
	public function get_user_info(){
		//参数接收
        $params = $this->getParams(1);//0 get 1 post 
		
		$user_id    	= intval(isset($params["user_id"]) ? $params["user_id"] : 0);
		$user_uid 		= intval(isset($params["user_uid"]) ? $params["user_uid"] : 0);
		
		//数据验证
        $Validate = validate('Publics', 'validate\publics');
        if( !$Validate -> scene('get_user_info') -> check($params) ){
            json_out(-1001, $Validate -> getError(), (object)[]);//验证失败
        }
		
		//逻辑处理
        $list = controller('Userlogic', 'logic\user') -> get_user_info($user_id, $user_uid);
		
		//数据返回
        if($list['code'] == 200){
            json_out(200, '获取成功', (object)$list['data']);      
        }else{
            json_out($list['code'], $list['message'], (object)[]);      
        }
    }
    
    /**
	 * 用户详情信息
	 * @author shiqiang <9761622041@qq.com>
	 * @return mixed
	 */
	public function login_auth_mobilenum(){
		//参数接收
        $params = $this->getParams(1);//0 get 1 post 
		
		$login_access_token    	= strval(isset($params["login_access_token"]) ? $params["login_access_token"] : '');
		
		//数据验证
        $Validate = validate('Publics', 'validate\publics');
        if( !$Validate -> scene('login_auth_mobilenum') -> check($params) ){
            json_out(-1001, $Validate -> getError(), (object)[]);//验证失败
        }
		
		//逻辑处理
        $list = controller('Userlogic', 'logic\user') -> login_auth_mobilenum($login_access_token);
		
		//数据返回
        if($list['code'] == 200){
            json_out(200, '获取成功', (object)$list['data']);      
        }else{
            json_out($list['code'], $list['message'], (object)[]);      
        }
    }
    
	
	/**
	 * 刷新token
	 * @author shiqiang <9761622041@qq.com>
	 * @return mixed
	 */
	public function oauth2_refresh_token(){
		//参数接收
        $params = $this->getParams(1);//0 get 1 post 
		
		$uid       	   = intval(isset($params["user_id"]) ? $params["user_id"] : 0);
		$refresh_token = isset($params["refresh_token"]) ? $params["refresh_token"] : '';
		
		//数据验证
        $Validate = validate('Publics', 'validate\publics');
        if( !$Validate -> scene('refresh_token') -> check($params) ){
            json_out(-1001, $Validate -> getError(), (object)[]);//验证失败
        }
		
		//逻辑处理
        $list = controller('Userlogic', 'logic\user') -> refresh_token($uid, $refresh_token);
        
        //日志 记录
        $bodyinput = input();

        if(isset($bodyinput['user_id'])){
            //特殊日志记录
            if($bodyinput['user_id'] == 4){
                $lista = json_encode($list, true);
                trace($lista, 'input_params_uid4');
            }

            //特殊日志记录
            if($bodyinput['user_id'] == 114){
                $lista = json_encode($list, true);
                trace($lista, 'input_params_uid114');
            }
        }

		//数据返回
		if($list['code'] == 200){
			json_out(200, '刷新成功', (object)$list['data']);
		}else{
			json_out(-9003, $list['message'], (object)[]);
		}
	}

	/**
	 * 获取行业 
	 * @author shiqiang <9761622041@qq.com>
	 * @return mixed
	 */
	public function get_base_industry_classification(){
		//参数接收
        $params = $this->getParams(0);//0 get 1 post 
		
		// $uid       	   = intval(isset($params["user_id"]) ? $params["user_id"] : 0);
		
		//数据验证
        // $Validate = validate('Publics', 'validate\publics');
        // if( !$Validate -> scene('refresh_token') -> check($params) ){
            // json_out(-1001, $Validate -> getError(), (object)[]);//验证失败
        // }
		
		//逻辑处理
        $list = controller('Userlogic', 'logic\user') -> get_base_industry_classification();
		
		//数据返回
		if($list['code'] == 200){
			json_out(200, '获取成功', (array)$list['data']);
		}else{
			json_out($list['code'], $list['message'], (array)[]);
		}
    }
    
    /**
	 * 获取登录得视频信息
	 * @author shiqiang <9761622041@qq.com>
	 * @return mixed
	 */
	public function get_base_login_video(){
		//参数接收
        $params = $this->getParams(0);//0 get 1 post 
		
		//逻辑处理
        $list = controller('video/VideoPlay', 'datacache') -> getAliVideoInfoByVideoid($video_id= 'd8b05432f5084d378448471249db6a54');
		
		//数据返回
		if($list['code'] == 200){
			json_out(200, '获取成功', (array)$list['data']);
		}else{
			json_out($list['code'], $list['message'], (array)[]);
		}
    }
    
    /**
	 * 手动 token 过期
	 * @author shiqiang <9761622041@qq.com>
	 * @return mixed
	 */
	public function oauth2_token_finash(){
		//参数接收
        $params = $this->getParams(0);//0 get 1 post 
		
        //逻辑处理
        $map = [];
        $map['uid'] = $params['user_id'];
        $data = [];
        $data['access_token_expire_time'] = 1;
        $rel = model('user_center/UcMemberAuthtoken', 'model\user') -> update($data, $map);

		//数据返回
		//if($list['code'] == 200){
			json_out(200, '获取成功');
		//}else{
			//json_out($list['code'], $list['message'], (array)[]);
		//}
    }

	/**
     * 测试使用
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function test(){
        //参数接收
        $params = $this->getParams(0);//0 get 1 post 
        
        
        dump(get_round_username());die;
        //逻辑处理
        $list = controller('common/Stslogic', 'logic') -> testSts();
        dump($list);
        //$rel = controller('common/Osslogic', 'logic') -> uploadFile();
        /* $key = 1;
        for($i = 14490000001; $i <= 14499999999; $i++) {
            if($key%10 == 0){
                dump($key);
                \think\Db::table('xm_uc_member_numper')->data($array)->insertAll();
                $array = [];
            }
            $array[] = [
                'mobile' => $i,
                'nick_name' => 'xm_'.$i,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $key++;
        } */
        //dump($array);
        //逻辑处理
        //$list = controller('video/VideoApilogic', 'logic') -> updatePalyStatusNormal($object='04a50a7a8b2a4227a813d423e10aa5ea');
        //dump($list);
        //数据返回
        //json_out($list['code'], $list['message'], $list['data']);      
    }

    /**
     * 支付成功回调
     * @author Naruto
     * @return json_out(code, message, data)
     */
    public function notify(){
        
        $xml = file_get_contents('php://input');
        //将服务器返回的XML数据转化为数组
        $data = $this->FromXml($xml);
        // 保存微信服务器返回的签名sign
        $data_sign = $data['sign'];
        // sign不参与签名算法
        unset($data['sign']);
        //$sign = self::makeSign($data);
        $sign = $this->makeSign($data);

        //增加一个日志
        //file_put_contents("userorder.txt".time(), json_encode($data));
        //$json = '{"appid":"wxf1ce5fccd088e469","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1600814121","nonce_str":"5mBnbKv0oHJGPPXD8cpbI2Y2rHGpVBOW","openid":"oip0n0jZsftjINjD5QKFPt0CSltI","out_trade_no":"20200908095845526168","result_code":"SUCCESS","return_code":"SUCCESS","time_end":"20200908095851","total_fee":"1","trade_type":"APP","transaction_id":"4200000698202009084501149709"}';
        //$data = json_decode($json, true);
  
        // 判断签名是否正确 判断支付状态
        if ( ($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') ) {
            //获取服务器返回的数据
            $order_num        = $data['out_trade_no'];   //订单单号
            $openid           = $data['openid'];         //付款人openID
            $total_fee        = $data['total_fee'];      //付款金额
            $transaction_id   = $data['transaction_id']; //微信支付流水号

            //验证订单 并且执行订单
            $data = controller('Publicslogic', 'logic') -> paySuccessOrderCz($order_num, $transaction_id);
            //$res = $this -> order_notice_data_deal($order_num,$openid,$total_fee,$transaction_id);
            dump($data);
            if ($data['code'] != 200) {
                $result = -2;
            } else {
                $result = 0;
            }
        }else{
          $result = -1;
        }

        // 返回状态给微信服务器https://apptest.hcbbs.com/index.php/api/User_vip/notify
        if ($result == 0) { // 成功之后不会再回调
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } elseif ($result == -1){ // 失败后会继续发送几次回调
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        } elseif ($result == -2) { // 失败后会继续发送几次回调
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[更改状态失败]]></return_msg></xml>';
        }
        //Clog::setLog($result,'order_notice_result');
        exit($str);
    }


    public function ToXml($array){
        if(!is_array($array)|| count($array) <= 0){
          return ;
        }
        $xml = '<xml version="1.0">';
        foreach ($array as $key=>$val){
          if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
          }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
          }
        }
        $xml.="</xml>";
        return $xml;
    }
    public function FromXml($xml){
        if(!$xml){
          // 人工抛出错误
          //throw new Exception("xml数据异常！");
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $this->values;
    }

    public function MakeSign($data)
    {
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string = $this->ToUrlParams($data);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=".'4a9f2c433adcc2698ba7704faedeaf82';
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }
    public function ToUrlParams($array)
    {
        $buff = "";
        foreach ($array as $k => $v)
        {
          if($k != "sign" && $v != "" && !is_array($v)){
            $buff .= $k . "=" . $v . "&";
          }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    // createNonceStr
    public function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ ) {
          $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

    /**
     * 申请团长 下拉参数
     * @author shiqiang
     * @return json_out(code, message, data)
     */
    public function apply_team_leader(){
        //逻辑处理
        $uc_apply_city          = config('uc_apply_city');
        $uc_apply_attributes    = config('uc_apply_attributes');
        $uc_apply_experience    = config('uc_apply_experience');
        $uc_apply_wechat_group  = config('uc_apply_wechat_group');

        $list = [
            'uc_apply_city'         => $uc_apply_city,
            'uc_apply_attributes'   => $uc_apply_attributes,
            'uc_apply_experience'   => $uc_apply_experience,
            'uc_apply_wechat_group' => $uc_apply_wechat_group,
        ];

        //数据返回
        json_out(200, '获取成功', $list);
    }

    /**
     * 申请供应商 下拉参数
     * @author shiqiang
     * @return json_out(code, message, data)
     */
    public function apply_supplier(){
        //逻辑处理

        $uc_apply_supplier_type  = config('uc_apply_supplier_type');
        $uc_apply_class_temp    = config('uc_apply_class_temp');

        $list = [
            'uc_apply_supplier_type'  => $uc_apply_supplier_type,
            'uc_apply_class_temp'     => $uc_apply_class_temp,
        ];

        //数据返回
        json_out(200, '获取成功', $list);
    }
}
